import { defineStore } from "pinia";
import { loginApi } from "@/api/user";
import { useTabsStore } from "./tabs";
import { 
    STORE_IDS, 
    STORAGE_KEYS, 
    DEFAULT_VALUES, 
    ERROR_MESSAGES,
    LoginParams,
    getStorageItem,
    getStorageArray,
    setStorageItem,
    setStorageArray,
    clearStorageItem
} from '@/constants/auth'

export const useUserStore = defineStore(STORE_IDS.USER, {
    state: () => ({
        token: getStorageItem(STORAGE_KEYS.TOKEN),
        roles: getStorageArray(STORAGE_KEYS.ROLES),
        username: getStorageItem(STORAGE_KEYS.USERNAME),
        nickname: getStorageItem(STORAGE_KEYS.NICKNAME),
        menu: getStorageArray(STORAGE_KEYS.MENU),
        xToken: getStorageItem(STORAGE_KEYS.X_TOKEN),
    }),
    actions: {
        async login(data: LoginParams) {
            try {
                const { data: { token, user: { username, roles, nickname }, menulist } } = await loginApi(data);
                
                // 更新store状态
                this.token = token
                this.roles = roles
                this.menu = menulist
                this.username = username
                this.nickname = nickname
                
                // 保存到localStorage
                setStorageItem(STORAGE_KEYS.TOKEN, token)
                setStorageArray(STORAGE_KEYS.ROLES, roles)
                setStorageItem(STORAGE_KEYS.USERNAME, username)
                setStorageItem(STORAGE_KEYS.NICKNAME, nickname)
                setStorageArray(STORAGE_KEYS.MENU, menulist)
                
                // 保存X-Token到localStorage
                if (token) {
                    setStorageItem(STORAGE_KEYS.X_TOKEN, token)
                }
            } catch (error) {
                console.error(ERROR_MESSAGES.LOGIN_FAILED, error);
                throw error; // 重新抛出错误，让调用方处理
            }
        },
        logout() {
            // 关闭除首页以外的所有选项卡
            const tabsStore = useTabsStore()
            tabsStore.clearAllTabsExceptHome()
            
            // 清空store状态
            this.token = DEFAULT_VALUES.TOKEN
            this.roles = DEFAULT_VALUES.ROLES
            this.username = DEFAULT_VALUES.USERNAME
            this.nickname = DEFAULT_VALUES.NICKNAME
            this.menu = DEFAULT_VALUES.MENU
            this.xToken = DEFAULT_VALUES.X_TOKEN
            
            // 清空localStorage
            localStorage.clear()
            // 确保清除X-Token
            clearStorageItem(STORAGE_KEYS.X_TOKEN)
        }
    }
})